import { AccessLevel, SingletonProto } from '@eggjs/tegg';
import { HttpException } from '@/core/HttpException';
import { randomBytes, createCipheriv, createHash, createDecipheriv } from 'crypto'

/**
 * 加解密工具
 */
@SingletonProto({
    accessLevel: AccessLevel.PUBLIC
})
export class CryptoUtils {

    /**
     * 加密函数
     * @param text 字符串
     * @param password 加密字符串
     * @returns 
     */
    encrypt(text: string, password: string) {
        const iv = randomBytes(16); // 初始化向量
        const cipher = createCipheriv('aes-256-cbc', createHash('sha256').update(password).digest(), iv);
        let encrypted = cipher.update(text);
        encrypted = Buffer.concat([encrypted, cipher.final()]);
        return iv.toString('hex') + ':' + encrypted.toString('hex');
    }

    /**
     * 解密函数
     * @param text 加密字符串
     * @param password 解密字符串
     * @returns 
     */
    decrypt(text: any, password: string) {
        try {
            const textParts = text.split(':');
            const iv = Buffer.from(textParts.shift(), 'hex');
            const encryptedText = Buffer.from(textParts.join(':'), 'hex');
            const decipher = createDecipheriv('aes-256-cbc', createHash('sha256').update(password).digest(), iv);
            let decrypted = decipher.update(encryptedText);
            decrypted = Buffer.concat([decrypted, decipher.final()]);
            return decrypted.toString();
        } catch (error: any) {
            throw new HttpException("", "错误的请求参数！")
        }
    }
}